package com.zs.grain.tool

import android.app.Application
import android.util.Base64
import android.widget.Toast
import com.jeremyliao.liveeventbus.LiveEventBus
import com.xnkj1688.semplibrary.mvvm.BaseViewModel
import com.zs.grain.service.DataService
import com.zs.grain.service.DeviceService
import com.zs.grain.service.SignalRService
import io.reactivex.Completable
import io.reactivex.Observable
import io.reactivex.schedulers.Schedulers
import java.io.File
import java.io.FileOutputStream
import java.sql.Date
import javax.inject.Inject

class DataSync @Inject constructor(
    val mApp:Application,
    val mDataService:DataService,
    val mSignalRService: SignalRService,
    val mDeviceService: DeviceService
    ):BaseViewModel(mApp){

    fun syncSettings(getType:String,mcb:Boolean,pcb:Boolean,scb:Boolean){
        if(scb){
            mSignalRService.settings
                .map {
                    var server = mDataService.server;

                    mDataService.DaoSetting.deleteAll();
                    mDataService.DaoSetting.insertInTx(it.toList());
                    if (server != mDataService.server)
                        mSignalRService.init("http://" + mDataService.server)
//                    this.terminalId.postValue(mDataService.terminalId.toString())
//                    this.verifyCode.postValue(mDataService.verifyCode)
//                    this.server.postValue(mDataService.server)

                    mDeviceService.init();
                    it.size
                }
                .map {
                    //uiNotify.postValue(super.getToastNotify("终端配置同步成功(${it}条)", Toast.LENGTH_SHORT))
                    mDataService.insertLog("$getType:终端配置同步成功(${it}条)")
                }
                .flatMap {
                    mSignalRService.advertisements
                }.map {
                    mDataService.DaoAdvertisement.deleteAll()
                    mDataService.DaoAdvertisement.insertInTx(it.toList())
                    it.size
                }.map {
                    //uiNotify.postValue(super.getToastNotify("广告数据同步成功(${it}条)", Toast.LENGTH_SHORT))
                    mDataService.insertLog("$getType:广告数据同步成功(${it}条)")
                }.subscribe({
                    //uiNotify.postValue(super.getToastNotify("系统数据同步成功", Toast.LENGTH_SHORT))
                    mDataService.insertLog("$getType:系统数据同步成功")
                },{
                    //uiNotify.postValue(super.getToastNotify("系统数据同步失败",Toast.LENGTH_SHORT))
                    mDataService.insertLog("$getType:系统数据同步失败")
                })
        }

        if(pcb){
            mSignalRService.settings
                .flatMap {
                    mSignalRService.menus
                }.map {
                    mDataService.DaoMenu.deleteAll()
                    mDataService.DaoMenu.insertInTx(it.toList())
                    it.size
                }.map {
                    //uiNotify.postValue(super.getToastNotify("菜单数据同步成功(${it}条)", Toast.LENGTH_SHORT))
                    mDataService.insertLog("$getType:菜单数据同步成功(${it}条)")
                }.flatMap {
                    mSignalRService.categories
                }.map {
                    mDataService.DaoCategory.deleteAll()
                    mDataService.DaoCategory.insertInTx(it.toList())
                    it.size
                }.map {
                    //uiNotify.postValue(super.getToastNotify("分类数据同步成功(${it}条)", Toast.LENGTH_SHORT))
                    mDataService.insertLog("$getType:分类数据同步成功(${it}条)")
                }.flatMap {
                    mSignalRService.goods
                }.map {
                    mDataService.DaoGood.deleteAll()
                    mDataService.DaoGood.insertInTx(it.toList())
                    it.size
                }.map {
                    //uiNotify.postValue(super.getToastNotify("商品数据同步成功(${it}条)", Toast.LENGTH_SHORT))
                    mDataService.insertLog("$getType:商品数据同步成功(${it}条)")
                }.flatMap {
                    mSignalRService.ingridents
                }.map {
                    mDataService.DaoIngrident.deleteAll()
                    mDataService.DaoIngrident.insertInTx(it.toList())
                    it.size
                }.map {
                    //uiNotify.postValue(super.getToastNotify("原料数据同步成功(${it}条)", Toast.LENGTH_SHORT))
                    mDataService.insertLog("$getType:商品数据同步成功(${it}条)")
                }
                .flatMap {
                    mSignalRService.receipes
                }.map {
                    mDataService.DaoReceipe.deleteAll()
                    mDataService.DaoReceipe.insertInTx(it.toList())
                    it.size
                }.map {
                    //uiNotify.postValue(super.getToastNotify("配方数据同步成功(${it}条)", Toast.LENGTH_SHORT))
                    mDataService.insertLog("$getType:配方数据同步成功(${it}条)")
                }
                .flatMap {
                    mSignalRService.images
                }.map {
                    mDataService.DaoImage.deleteAll()
                    mDataService.DaoImage.insertInTx(it.toList())
                    it
                }.map {
                    //uiNotify.postValue(getToastNotify("图片数据同步成功(${it.size})条)", Toast.LENGTH_SHORT))//size
                    mDataService.insertLog("$getType:图片数据同步成功(${it.size})条)")//
                    it
                }.toObservable()
                .flatMap {
                    var dir = File(mDataService.imagesPath)
                    if (!dir.exists()) dir.mkdir()
                    Observable.fromIterable(it.toList())
                }.observeOn(Schedulers.newThread())
                .map {
                    val fileName = "${mDataService.imagesPath}/${it.getFileName()}"
                    var file = File(fileName)
                    if ((file.exists() && it.remark == null) || (it.remark != null && file.lastModified() >= Date.valueOf(
                            it.remark
                        ).getTime())
                    )
                        return@map

                    var single = mSignalRService.getImage(it.id)
                    single.map {
                        var data = Base64.decode(it, Base64.NO_WRAP);
                        var fos = FileOutputStream(file);
                        fos.write(data);
                        fos.close();
                    }.subscribe({
                        //uiNotify.postValue(getToastNotify("图片下载成功:\n${file.name}", Toast.LENGTH_SHORT))
                        mDataService.insertLog("$getType:图片下载成功:${file.name}")
                    }, {
                        //uiNotify.postValue(super.getToastNotify("图片下载失败:\n${file.name}", Toast.LENGTH_LONG))
                        mDataService.insertLog("$getType:图片下载失败:${file.name}")
                    })
                    Completable.fromSingle(single).blockingGet()
                }
                .subscribe({
                },{
                    //uiNotify.postValue(super.getToastNotify("产品数据同步失败", Toast.LENGTH_SHORT))
                    mDataService.insertLog("$getType:产品数据同步失败")
                },{
                    //uiNotify.postValue(super.getToastNotify("产品数据同步成功", Toast.LENGTH_SHORT))
                    mDataService.insertLog("$getType:产品数据同步成功")
                })
        }

        if(mcb){
            mSignalRService.settings
                .flatMap {
                    mSignalRService.components
                }.map {
                    if(it.size<=0){
                        var components = mDeviceService.components
                        mDataService.update(components)
                        LiveEventBus.get("SyncService.UploadComponents").post(0)
                    }else {
                        mDataService.DaoComponent.deleteAll()
                        mDataService.DaoComponent.insertInTx(it.toList())
                    }
                    it.size
                }.map {
                    //uiNotify.postValue(super.getToastNotify("部件数据同步成功(${it}条)", Toast.LENGTH_SHORT))
                    mDataService.insertLog("$getType:部件数据同步成功(${it}条)")
                }.flatMap {
                    mSignalRService.adjustments
                }.map {
                    mDataService.DaoAdjustment.deleteAll()
                    mDataService.DaoAdjustment.insertInTx(it.toList())
                    mDeviceService.setAdjustments()
                    it.size
                }.map {
                    //uiNotify.postValue(super.getToastNotify("部件参数同步成功(${it}条)", Toast.LENGTH_SHORT))
                    mDataService.insertLog("$getType:部件参数同步成功(${it}条)")
                }
                .subscribe({showToast("机器数据同步成功", Toast.LENGTH_LONG)
                    mDataService.insertLog("$getType:机器数据同步成功")
                }, {
                    //uiNotify.postValue(super.getToastNotify("机器数据同步失败", Toast.LENGTH_SHORT))
                    mDataService.insertLog("$getType:机器数据同步失败")
                })
        }
    }
}